<template>
  <ContentWrap>
    <div class="tongue-basic-config">
      <el-form label-position="left" label-width="120px">
        <el-form-item label="插件开关">
          <el-switch v-model="formData.pluginSwitch" :active-value="1" :inactive-value="0" />
        </el-form-item>
 <!-- 引流开关 -->
        <el-form-item label="是否引流">
          <el-switch v-model="formData.isDrainage" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <!-- 购买方式 -->
        <el-form-item label="购买方式:">
          <div class="purchase-methods">
            <div v-for="item in purchaseList" :key="item.value">
              <div class="purchase-method">
                <el-checkbox v-model="item.checked">{{ item.label }}</el-checkbox>
                <div class="purchase-inputs">
                  <div class="input-item">
                    <span class="input-label">次数</span>
                    <el-input type="number" v-model="item.count" />
                  </div>
                </div>
                <el-button type="text" @click="onSelect(item.value)">关联商品</el-button>
              </div>
              <SpuAndSkuList
                ref="spuAndSkuListRef"
                :spu-list="item.spuList"
                :spu-property-list-p="item.spuPropertyList"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="分享卡片图片" prop="appletPic">
          <UploadImg v-model="formData!.appletPic" :limit="1">
            <template #tip
              >用于微信分享时显示的卡片图片，建议尺寸 300x300px;显示图片长宽比是 5:4;</template
            >
          </UploadImg>
        </el-form-item>
        <!-- 小程序路径和H5链接 -->
        <div class="url-row">
          <div class="url-item">
            <span class="text-right">小程序路径地址</span>
            <el-input v-model="formData.appletUrl" />
            <el-button
              :disabled="!formData.pluginSwitch"
              @click="copyToClipboard(formData.appletUrl)"
              >复制</el-button
            >
          </div>
        </div>
        <div class="url-row">
          <div class="url-item">
            <span class="text-right">H5 路径</span>
            <el-input v-model="formData.h5Url" />
            <el-button :disabled="!formData.pluginSwitch" @click="copyToClipboard(formData.h5Url)"
              >复制</el-button
            >
          </div>
        </div>

        <!-- 赠送开关 -->
        <el-form-item label="赠送开关:">
          <el-switch v-model="formData.sendSwitch" :active-value="1" :inactive-value="0" />
          <span class="switch-desc">用户界面可将次数赠送给好友</span>
        </el-form-item>

        <!-- 新用户免费赠送次数 -->
        <el-form-item label="新用户免费赠送次数:">
          <div class="input-with-unit">
            <el-input v-model="formData.newUserTimes" style="width: 200px" />
            <span class="unit">次</span>
          </div>
        </el-form-item>

        <!-- 会员等级和赠送次数 -->
        <div class="member-levels">
          <div v-for="(level, index) in memberLevels" :key="index" class="member-level-item">
            <div class="member-level-row">
              <div class="member-level-select">
                <span>会员等级:</span>
                <el-select v-model="level.level" class="!w-150px" placeholder="请选择会员等级">
                  <el-option
                    v-for="item in levelList"
                    :disabled="memberLevels.some((member) => member.level === item.level)"
                    :key="item.level"
                    :label="item.name"
                    :value="item.level"
                  />
                </el-select>
              </div>

              <div class="gift-count">
                <span>赠送次数:</span>
                <el-input type="number" v-model="level.count" style="width: 150px" />
                <span>次</span>
              </div>

              <div class="level-actions">
                <el-button
                  type="primary"
                  plain
                  size="small"
                  v-if="index === memberLevels.length - 1"
                  @click="addMemberLevel"
                  >新增</el-button
                >
                <el-button
                  type="danger"
                  plain
                  size="small"
                  v-if="index !== 0"
                  @click="removeMemberLevel(index)"
                  >删除</el-button
                >
              </div>
            </div>
          </div>
        </div>

        <!-- 隐私协议开关 -->
        <el-form-item label="隐私协议">
          <el-switch v-model="formData.privacyPolicySwitch" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <!-- 隐私协议内容 -->
        <div class="editor-section" v-if="formData.privacyPolicySwitch">
          <div class="editor-title">隐私协议内容</div>
          <div class="editor-container">
            <Editor v-model="formData.privacyPolicyContent" :height="300" />
          </div>
        </div>

        <!-- 智能咨询介绍 -->
        <div class="editor-section">
          <div class="editor-title">智能舌面珍介绍页</div>
          <div class="editor-container">
            <Editor v-model="formData.tongueIntro" :height="300" />
          </div>
        </div>

        <!-- 购买协议开关 -->
        <el-form-item label="购买协议">
          <el-switch v-model="formData.buyPolicySwitch" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <!-- 协议名称 -->
        <el-form-item label="协议名称" v-if="formData.buyPolicySwitch">
          <el-input v-model="formData.buyPolicyName" style="width: 500px" />
        </el-form-item>

        <!-- 协议内容 -->
        <div class="editor-section" v-if="formData.buyPolicySwitch">
          <div class="editor-title">协议内容</div>
          <div class="editor-container">
            <Editor v-model="formData.buyPolicyContent" :height="300" />
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="submitForm">提交</el-button>
        </div>
      </el-form>
    </div>
    <SpuSelect ref="spuSelectRef" :isSelectSku="true" :radio="true" @confirm="selectSpu" />
  </ContentWrap>
</template>

<script setup lang="ts">
import { reactive, ref, toRefs, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Editor } from '@/components/Editor'
import { TongueBasicApi } from '@/api/application/tongue/basic'
import * as LevelApi from '@/api/member/level'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import { SpuAndSkuList, SpuSelect } from '@/views/mall/promotion/components'
import { getPropertyList } from '@/views/mall/product/spu/components'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { disableCache } from '@purge-icons/generated'
const spuSelectRef = ref() // 商品和属性选择 Ref
const spuAndSkuListRef = ref() // sku 秒杀配置组件Ref
const spuList = ref<[]>([]) // 选择的 spu
/** 查询会员等级列表 */
const getLevel = async () => {
  levelList.value = await LevelApi.getLevelList({})
}
const purchaseList = ref(getDictOptions(DICT_TYPE.TONGUE_BILLING_METHOD))
const levelList = ref([])
const selectedValue = ref<any>(null)
onMounted(() => {
  getLevel()
  getDetails()
})
// 表单数据
const formData = reactive({
  pluginSwitch: 0,
  appletUrl: '/pages/tongue/index',
  appletPic: '',
  h5Url: '',
  sendSwitch: 0,
  newUserTimes: 0,
  privacyPolicySwitch: 0,
  privacyPolicyContent: '',
  tongueIntro: '',
  buyPolicySwitch: 0,
  buyPolicyName: '',
  buyPolicyContent: '',
  purchaseConfig: '',
  memberLevelConfig: '',
  isDrainage:0
})

// 会员等级列表
const memberLevels = ref([{ level: '', count: null }] as any)

// 添加会员等级
const addMemberLevel = () => {
  memberLevels.value.push({
    level: '',
    count: null
  })
}

// 删除会员等级
const removeMemberLevel = (index: number) => {
  if (index !== 0) {
    // 第一个不能删除
    memberLevels.value.splice(index, 1)
  }
}
const selectSpu = async (spuId: number, skuIds: number[]) => {
  const selectedItem = purchaseList.value.find((item) => item.value === selectedValue.value)
  selectedItem.spuId = spuId
  selectedItem.skuId = skuIds[0]
  const { spu, spuProperties } = await getSpuDetails(spuId, skuIds)
  console.log('spu', spu)
  selectedItem.spuList = [spu]
  selectedItem.spuPropertyList = spuProperties
  selectedItem.price = spu.skus[0].price
}
const onSelect = (val) => {
  selectedValue.value = val
  spuSelectRef.value.open()
}
const copyToClipboard = (text: string) => {
  navigator.clipboard.writeText(text).then(() => {
    ElMessage({
      message: '复制成功',
      type: 'success'
    })
  })
}
const getSpuDetails = async (spuId: number, skuIds: number[] | undefined) => {
  const spuProperties: any[] = []
  const res = await ProductSpuApi.getSpuDetailList([spuId])
  if (res.length == 0) {
    return
  }
  spuList.value = []
  // 因为只能选择一个
  const spu = res[0]
  const selectSkus =
    typeof skuIds === 'undefined' ? spu?.skus : spu?.skus?.filter((sku) => skuIds.includes(sku.id!))

  spu.skus = selectSkus
  spuProperties.push({
    spuId: spu.id!,
    spuDetail: spu,
    propertyList: getPropertyList(spu)
  })
  return { spu, spuProperties }
}
const getDetails = () => {
  TongueBasicApi.getTongueBasice().then((res) => {
    Object.assign(formData, res)
    memberLevels.value = res.memberLevelConfig && JSON.parse(res.memberLevelConfig)
    const arr = res.purchaseConfig && JSON.parse(res.purchaseConfig)
    // purchaseList.value =
    purchaseList.value.forEach(async (item) => {
      // 检查当前项的 value 是否在 arr 中
      const matchedObj = arr.find((obj) => obj.type === item.value)
      if (matchedObj) {
        const { spu, spuProperties } = await getSpuDetails(matchedObj.spuId, [matchedObj.skuId])
        item.checked = true
        item.spuList = [spu]
        item.price = spu.skus[0].price
        item.spuPropertyList = spuProperties
        item.spuId = matchedObj.spuId
        item.skuId = matchedObj.skuId
        item.count = matchedObj.count
      }
    })
    console.log('purchaseList.value', purchaseList.value)
  })
}
// 提交表单
const submitForm = () => {
  // 表单验证逻辑
  const isAnyChecked = purchaseList.value.some((item) => item.checked)
  if (!isAnyChecked) {
    ElMessage.warning('至少选择一种购买方式')
    return // 阻止后续逻辑执行
  }

  // 会员等级验证
  for (const level of memberLevels.value) {
    level.count = Number(level.count)
    if (!level.count || level.count === 0) {
      ElMessage.warning('请填写会员等级的赠送次数')
      return
    }
    if (!level.level) {
      ElMessage.warning('请选择会员等级')
      return
    }
  }
  const purchaseConfig = [...purchaseList.value]
    .filter((item) => item.checked)
    .map((item) => {
      if (!item.spuList || item.spuList.length === 0) {
        ElMessage.warning(`请选择${item.label}的关联商品`)
        return
      }
      if (!item.count || item.count === 0) {
        ElMessage.warning(item.label + '的购买数量不能为0')
        return
      }
      const obj = {
        type: item.value,
        spuId: item.spuId,
        skuId: item.skuId,
        price: Number(item.price),
        count: Number(item.count)
      }
      return obj
    })
  const postData = {
    ...formData,
    purchaseConfig: JSON.stringify(purchaseConfig),
    memberLevelConfig: JSON.stringify(memberLevels.value)
  }
  console.log('obj', postData)
  TongueBasicApi.setTongueBasice(postData).then((res) => {
    getDetails()
    ElMessage.success('配置保存成功')
  })
}
</script>

<style scoped lang="scss">
.tongue-basic-config {
  padding: 20px 0;

  .el-form {
    padding: 24px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 5%);
  }

  .el-form-item {
    margin-bottom: 22px;
  }

  .purchase-methods {
    display: flex;
    flex-direction: column;
    gap: 18px;
    margin-bottom: 10px;
  }

  .purchase-method {
    display: flex;
    align-items: center;
    gap: 24px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 6px;

    .el-checkbox {
      width: 70px;
    }

    .purchase-inputs {
      display: flex;
      gap: 20px;
    }

    .input-item {
      display: flex;
      align-items: center;
      gap: 10px;

      .input-label {
        width: 40px;
        color: #606266;
      }

      .el-input {
        width: 150px;
      }
    }
  }

  .url-row {
    display: flex;
    margin-bottom: 20px;
    gap: 20px;

    .url-item {
      flex: 1;
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      background-color: #f8f9fa;
      border-radius: 6px;

      span {
        font-size: 14px;
        color: #606266;
        white-space: nowrap;
      }

      .el-input {
        flex: 1;
      }

      .el-button {
        margin-left: 5px;
      }
    }
  }

  .switch-desc {
    margin-left: 12px;
    font-size: 14px;
    color: #909399;
  }

  .input-with-unit {
    display: flex;
    align-items: center;
    gap: 12px;

    .unit {
      color: #606266;
    }
  }

  .member-levels {
    padding: 16px;
    margin: 24px 0;
    background-color: #f8f9fa;
    border-radius: 8px;

    .member-level-item {
      padding: 16px;
      margin-bottom: 16px;
      background-color: #fff;
      border-radius: 6px;
      box-shadow: 0 1px 4px rgb(0 0 0 / 5%);
    }

    .member-level-row {
      display: flex;
      align-items: center;
      gap: 20px;
    }

    .member-level-select,
    .gift-count {
      display: flex;
      align-items: center;
      gap: 12px;

      span {
        min-width: 70px;
        font-size: 14px;
        color: #606266;
      }
    }

    .level-actions {
      margin-left: auto;
    }
  }

  .editor-section {
    padding: 20px;
    margin: 30px 0;
    background-color: #f8f9fa;
    border-radius: 8px;

    .editor-title {
      padding-bottom: 12px;
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      border-bottom: 1px solid #ebeef5;
    }

    .editor-container {
      overflow: hidden;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
    }
  }

  .form-actions {
    display: flex;
    padding-top: 24px;
    margin-top: 40px;
    border-top: 1px solid #ebeef5;
    justify-content: center;

    .el-button {
      padding: 12px 30px;
      font-size: 16px;
    }
  }
}
</style>
